﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls;
using Passwords.Models;
using Passwords.Controllers;
using Silvermoon.UI;
using Silvermoon.OpenGL;
using Passwords.Styles;
using Silvermoon.Debug;
using Silvermoon.Windows;
using Passwords.Controls;
using Silvermoon.Windows.Styles;
using Silvermoon.Navigation;
using Passwords.Biz;
using Silvermoon.Images;
using Passwords.Utils;

namespace Passwords.Pages
{
    public class PasswordsPage : Page
    {
        public PasswordsTab TabView { get; private set; }
        private SearchPicker searchPicker;
        private PasswordsController controller;

        public readonly PasswordItemContextMenu PasswordItemContextMenu = new PasswordItemContextMenu();

        public PasswordsPage()
            : base()
        {
            InitializePage();
        }

        protected override void Dispose(bool dispose)
        {
            DisposeObject(PasswordItemContextMenu);
            DisposeObject(controller);
            base.Dispose(dispose);
            DebuggerWindow.Monitor = false;
            PasswordCommands.Password.Executed -= Password_Executed;
            PasswordCommands.EditPassword.Executed -= OnEditPassword;
            PasswordCommands.FilterPasswords.Executed -= OnFilterChanged;
            PasswordCommands.ChangeFave.Executed -= OnAddFave;
        }


        protected override void OnHiding()
        {
            searchPicker.IsShowing = false;
            PasswordsControllerHelper.TextToHighlight = string.Empty;
            base.OnHiding();
        }

        private void InitializePage()
        {
            Title = "PASSWORDS";
            Styles = StylePool.Metro;
            TabView = new PasswordsTab();
            TabView.PageChanged += new EventHandler(OnPageChanged);
            TabView.PageChanging += OnPageChanged;
            searchPicker = new SearchPicker { Margin = new Margin(0, 0, 0, null) };
            searchPicker.TextChanged += new EventHandler(searchPicker_TextChanged);
            Controls.Add(TabView);
            VisibleControls.AddLast(searchPicker);
            Style = StylePool.Window;
            controller = new PasswordsController(this);
            PasswordCommands.Password.Executed += new EventHandler<CommandEventArgs>(Password_Executed);
            PasswordCommands.EditPassword.Executed += OnEditPassword;
            PasswordCommands.FilterPasswords.Executed += new EventHandler<CommandEventArgs>(OnFilterChanged);
            PasswordCommands.ChangeFave.Executed += OnAddFave;

            Toolbar toolbar = new Toolbar();
            toolbar.AddButton(SysImages.Add, PasswordCommands.NewPassword);
            toolbar.AddButton(SysImages.Find, PasswordCommands.FilterPasswords);

            toolbar.Styles.SetClass<MenuItem>(new TextItemStyle { Font = FontCache.MediumRegularFont, Padding = new Margin(20, 0, 20, 0) });
            toolbar.AddMenuItem("Edit Categories").Tap += OnEditCategories;
            toolbar.AddMenuItem("Edit Labels").Tap += OnEditLabels;
            toolbar.AddMenuItem("Sync with Server").Enabled = false;
            toolbar.AddMenuItem("Export").Enabled = false;

            Toolbar = toolbar;

        }

        void OnEditLabels(object sender, EventArgs e)
        {
            LabelPickerPage page = new LabelPickerPage();
            (Window as Page).NavigateTo(page);
        }

        void OnEditCategories(object sender, EventArgs e)
        {
            CategoryPickerPage page = new CategoryPickerPage();
            (this.Window as Page).NavigateTo(page);
        }


        void OnAddFave(object sender, CommandEventArgs e)
        {
            controller.AllPasswordsController.BindItems();
            controller.CategoryPasswordController.BindItems();
            //TabView.AllListView.InvalidateItems();
            //TabView.CategoriesListView.InvalidateItems();
        }

        void OnPageChanged(object sender, EventArgs e)
        {
            if (TabView.Pages.Count > 0 && TabView.SelectedPage != TabView.Pages[0])
            {
                if (searchPicker.IsShowing)
                {
                    OnFilterChanged(sender, e);
                }
                IsKeyboardVisible = false;
            }
        }

        void searchPicker_TextChanged(object sender, EventArgs e)
        {
            if (searchPicker != null && controller != null)
            {
                PasswordsControllerHelper.TextToHighlight = searchPicker.Filter;
                controller.AllPasswordsController.DataSource = GetFilteredPasswords(searchPicker.Filter);
            }
        }

        void OnFilterChanged(object sender, EventArgs e)
        {
            searchPicker.IsShowing ^= true;
            if (searchPicker.IsShowing)
            {
                TabView.GotoSearchPage();
                controller.AllPasswordsController.GroupDescriptors.Clear();
                controller.AllPasswordsController.DataSource = Context.Current.Passwords;
            }
            else
            {
                PasswordsControllerHelper.SetControllerAzIndex(controller.AllPasswordsController);
                controller.AllPasswordsController.DataSource = Context.Current.Passwords;
            }
            if (!searchPicker.IsShowing) searchPicker.Filter = "";
        }

        private IEnumerable<Password> GetFilteredPasswords(string filter)
        {
            if (string.IsNullOrEmpty(filter)) return Context.Current.Passwords.ToList();
            var list = from p in Context.Current.Passwords where p.Name.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0 orderby p.Name select p;
            return list;

        }

        private void OnEditPassword(object sender, CommandEventArgs e)
        {
            Password password = e.Object as Password;
            EditDetailsPage page = new EditDetailsPage { Password = password };
            this.NavigateTo(page);
        }

        void Password_Executed(object sender, CommandEventArgs e)
        {
            Password password = e.Object as Password;
            DetailsPage detailsView = new DetailsPage { Password = password };
            this.NavigateTo(detailsView);
        }

        private class Bag
        {
            public int AllOffset;
            public int CategoriesOffset;
            public int FavesOffset;
        }

        public override object OnSaveViewState()
        {
            return new Bag
            {
                AllOffset = TabView.AllListView.YOffset,
                CategoriesOffset = TabView.CategoriesListView.YOffset,
                FavesOffset = TabView.FavesListView.YOffset
            };
        }

        public override void OnLoadViewState(object viewState)
        {
            Bag bag = viewState as Bag;
            if (bag != null)
            {
                TabView.AllListView.YOffset = bag.AllOffset;
                TabView.CategoriesListView.YOffset = bag.CategoriesOffset;
                TabView.FavesListView.YOffset = bag.FavesOffset;
            }
        }
    }
}
